<template>
  <div class="login-container">
    <el-tabs :stretch="true" type="border-card" style="width: 400px;height: 330px;" class="demo-tabs">
      <el-tab-pane label="账号登录">
        <login-form></login-form>
      </el-tab-pane>
      <el-tab-pane label="扫码登录">
        <div v-if="!loading">
          <app-avatar style="margin-top: 10px;" :size="200" :src="image"></app-avatar>
          <div style="margin-top: 10px;">
            <span>微信 扫一扫 登录 </span>
          </div>
          <span v-if="errorMsg" class="errorText">{{ errorMsg }}</span>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {UUID} from "@/utils/constants";
import {getLoginCode} from "@/api/system";
import {Local} from "@/utils/storage";
import {store} from "@/store";
import {ElMessage} from "element-plus";
import {useRouter, useRoute} from 'vue-router';
import loginForm from './loginForm.vue'

const route = useRoute();
const router = useRouter();
const image = ref('')

const loading = ref(true)
const errorMsg = ref('暂不支持')

onMounted(async () => {
  let loginId = Local.get('login_id')
  if (!loginId) {
    const uuid = UUID()
    Local.set('login_id', uuid)
    loginId = uuid
  }
  // 獲取圖片
  const img = await getLoginCode(loginId as string)
  if (img.length === 0) {
    Local.remove('login_id')
  } else {
    image.value = img
    loading.value = false
    // 连接sse
    const url = import.meta.env.VITE_API_BASEURL
    const se = new EventSource(`${url}/openLoginOnline/${loginId}`)
    se.onerror = (e) => {
      errorMsg.value = '页面失效请刷新页面！'
      se.close()
    }
    se.onmessage = async (e) => {
      try {
        const data = JSON.parse(e.data)
        if (!data) {
          return;
        }
        await store.dispatch('user/login', data)
        ElMessage.success('登录成功');
        // 跳转回原来页面
        let redirect = route.query.redirect || '/';
        if (typeof redirect !== 'string') {
          redirect = '/';
        }
        await router.replace(redirect);
      } catch (err) {
        console.log('登录失败！', err)
      }
    }

  }
})

</script>

<style lang="scss" scoped>
.login-container {
  min-width: 400px;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: #2d3a4b;

  & > div {
    color: #000;
    font-size: 20px;
    text-align: center;
  }

}

span.errorText {
  color: #cc2828;
  margin-top: 10px;
  background: #eeeeee;
  padding: 10px;
  border-radius: 20px;
}

</style>
